package com.pt5.pthouduan.entity;

import com.pt5.pthouduan.service.PasskeyValidator;
import com.turn.ttorrent.bcodec.BEValue;
import com.turn.ttorrent.bcodec.InvalidBEncodingException;
import com.turn.ttorrent.common.protocol.TrackerMessage;
import com.turn.ttorrent.common.protocol.http.HTTPAnnounceRequestMessage;
import com.turn.ttorrent.common.protocol.http.HTTPTrackerErrorMessage;
import com.turn.ttorrent.tracker.TrackerRequestProcessor;
import com.turn.ttorrent.tracker.TorrentsRepository;
//import org.simpleframework.http.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class PasskeyTrackerProcessor extends TrackerRequestProcessor {

    private final PasskeyValidator passkeyValidator;
    private static final String[] NUMERIC_REQUEST_FIELDS = new String[]{
            "port", "uploaded", "downloaded", "left", "compact", "no_peer_id", "numwant"
    };

    public PasskeyTrackerProcessor(TorrentsRepository torrentsRepository,
                                   PasskeyValidator passkeyValidator) {
        super(torrentsRepository);
        this.passkeyValidator = passkeyValidator;
    }

    @Override
    public void process(String uri, String hostAddress, RequestHandler requestHandler)
            throws IOException {
        try {
            // 1. 使用自定义解析方法（已包含passkey检查）
            ParsedAnnounceRequest parsedRequest = parseQueryWithPasskey(uri, hostAddress);
            System.out.println(uri);

            // 2. 直接获取passkey（已在parseQueryWithPasskey中确保存在）
            String passkey = parsedRequest.getPasskey();

            // 3. 验证passkey
            if (!passkeyValidator.isValid(passkey)) {
                System.out.println("Invalid passkey: " + passkey);
                return ;
            }
            else {
                PasskeyContext.setPasskey(passkey);
                System.out.println("Valid passkey: " + passkey);
            }
            // 如果需要，可以将passkey存储在请求上下文中，供后续处理使用
            // 例如，通过ThreadLocal或其他方式
            // 4. 调用父类处理
            // 注意：这里假设父类的process方法不需要直接访问passkey
            // 如果需要，可能需要重构父类或传递passkey
            super.process(uri, hostAddress, requestHandler);
        } catch (Exception e) {
           System.out.println(e.getMessage());
           throw new RuntimeException("Failed to update peer stats", e); // 可根据需求决定是否抛出异常
        }
    }



    /**
     * 自定义解析逻辑，强制要求passkey参数，并返回解析后的请求对象
     */
    private ParsedAnnounceRequest parseQueryWithPasskey(String uri, String hostAddress)
            throws IOException, TrackerMessage.MessageValidationException {

        Map<String, BEValue> params = new HashMap<>();

        try {
            // 分割查询参数
            String query = uri.contains("?") ? uri.split("\\?")[1] : "";
            String[] pairs = query.split("&");

            for (String pair : pairs) {
                if (pair.isEmpty()) continue;

                String[] kv = pair.split("=", 2);
                String key = URLDecoder.decode(kv[0], StandardCharsets.ISO_8859_1.toString());
                String value = kv.length > 1 ? URLDecoder.decode(kv[1], StandardCharsets.ISO_8859_1.toString()) : "";

                // 处理数字型参数
                if (Arrays.asList(NUMERIC_REQUEST_FIELDS).contains(key)) {
                    try {
                        params.put(key, new BEValue(Long.parseLong(value)));
                    } catch (NumberFormatException e) {
                        throw new TrackerMessage.MessageValidationException(
                                "Invalid numeric value for field: " + key);
                    }
                } else {
                    params.put(key, new BEValue(value, StandardCharsets.ISO_8859_1.toString()));
                }
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new TrackerMessage.MessageValidationException("Invalid request format");
        }

        // 强制检查passkey
        if (!params.containsKey("passkey")) {
            throw new TrackerMessage.MessageValidationException("passkey is required");
        }

        // 如果未提供IP，使用客户端IP
        if (!params.containsKey("ip")) {
            params.put("ip", new BEValue(hostAddress, StandardCharsets.ISO_8859_1.toString()));
        }

        // 创建并返回自定义的ParsedAnnounceRequest对象
        return new ParsedAnnounceRequest(params);
    }
//    private void serveError(HttpStatus status, HTTPTrackerErrorMessage error, RequestHandler requestHandler) throws IOException {
//        requestHandler.serveResponse(status.getCode(), status.getDescription(), error.getData());
//    }
//
//    private void serveError(Status status, String error, RequestHandler requestHandler) throws IOException {
//        this.serveError(status, HTTPTrackerErrorMessage.craft(error), requestHandler);
//    }
//
//    private void serveError(Status status, TrackerMessage.ErrorMessage.FailureReason reason, RequestHandler requestHandler) throws IOException {
//        this.serveError(status, reason.getMessage(), requestHandler);
//    }


    /**
     * 自定义类用于存储解析后的请求参数
     */
    private static class ParsedAnnounceRequest {
        private final Map<String, BEValue> params;

        public ParsedAnnounceRequest(Map<String, BEValue> params) {
            this.params = params;
        }

        /**
         * 获取passkey参数
         */
        public String getPasskey() throws InvalidBEncodingException {
            BEValue passkeyValue = params.get("passkey");
            if (passkeyValue == null) {
                throw new IllegalStateException("passkey is missing");
            }
            return passkeyValue.getString();
        }

        /**
         * 获取其他参数（如果需要）
         */
        public BEValue getParam(String key) {
            return params.get(key);
        }

        // 可根据需要添加更多方法
    }
}